﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcJqGrid;
using PagedList;
using WebApp.Models;
using WebApp.Services;

namespace WebApp.Controllers
{
    public class SampleController : Controller
    {
        //
        // GET: /Sample/

        private SampleService _service;

        public ActionResult Index()
        {
            return View();
        }

        public JsonResult GetUsers(GridSettings gridSettings)
        {
            _service = new SampleService();

            var realCount = 0;

            var datas = _service.GetUsers(ref realCount);

            var lists = new List<UserModel>();
            foreach (var model in datas)
            {
                var item = new UserModel();
                item.user_id = model.user_id;
                item.user_fullname = model.user_firstname + " " + model.user_lastname;
                item.created_date = model.user_create_date.HasValue ? model.user_create_date.Value : DateTime.Now;

                lists.Add(item);
            }

            var totalBUs = realCount;
            var totalPage = totalBUs / gridSettings.PageSize;

            if (totalPage > Convert.ToInt32(totalPage))
            {
                totalPage = totalPage + 1;
            }

            var jsonData = new
            {
                total = Convert.ToInt32(totalPage),
                page = gridSettings.PageIndex,
                records = totalBUs,
                rows = (
                            from c in lists
                            select new
                            {
                                id = c.user_id,
                                cell = new[] {
                                            c.user_fullname,
                                            c.created_date.ToLongDateString()
                                            }
                            }
                        ).ToPagedList(1, gridSettings.PageSize).ToArray()
            };

            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

    }
}
